package main

import (
	"fmt"

	"gitee.com/go-micro-services/common"
	"gitee.com/go-micro-services/nacos-go-micro-gin/conf"
	"gitee.com/go-micro-services/nacos-go-micro-gin/routers"
	"github.com/gin-gonic/gin"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"go-micro.dev/v4/web"
)

func init() {
	// 1. 参数初始化
	initNacosParams()
	// 2. 注册
	regNacos()
	// 3. 监听
	listenNacosConfig()
}

// 参数初始化
func initNacosParams() {
	// 初始化配置，并在过程中修改默认值
	common.InitNacosParams(func(cfg *common.NacosParams) {
		cfg.NacosIp = conf.NacosIp
		cfg.NacosPort = conf.NacosPort
		cfg.NacosNamespaceId = conf.NacosNamespaceId
		cfg.NacosLogLevel = conf.NacosLogLevel
	})
	// 如果需要，可以随时通过GetCurrentConfig获取配置副本
	currentConfig := common.GetNacosCurrentParams()
	fmt.Printf("Retrieved Config - Service Name: %s, Port: %d\n", currentConfig.NacosIp, currentConfig.NacosPort)
}

// 注册
func regNacos() {
	_, err := common.NacosRegisterServiceInstance(vo.RegisterInstanceParam{
		Ip:          conf.NacosIp,
		Port:        conf.NacosPort,
		ServiceName: conf.NacosServiceName,
		GroupName:   conf.NacosGroupName,
		// ClusterName: "cluster-a",
		Weight:    10,
		Enable:    true,
		Healthy:   true,
		Ephemeral: true,
		Metadata:  conf.NacosMetadata,
	})
	if err != nil {
		fmt.Println("注册发生错误: ", err.Error())
	}
}

// 监听配置改动
func listenNacosConfig() {
	var namespace, group, dataId string
	err := common.NacosListenConfigWithCallback(conf.NacosDataId, conf.NacosGroup, func(namespace, group, dataId, data string) {
		namespace = namespace
		group = group
		dataId = dataId
		fmt.Println("Config changed. Namespace: %s, Group: %s, DataId: %s, Content: %s", namespace, group, dataId, data)
	})
	if err != nil {
		fmt.Println("Failed to listen config for Namespace: %s, DataId: %s, Group: %s. Error: %v", namespace, dataId, group, err)
	}
}

func main() {
	ginRouter := gin.Default()
	routers.RoutersInit(ginRouter)

	srv := web.NewService(
		web.Metadata(map[string]string{"version": "latest"}),
		web.Handler(ginRouter),      // 服务路由
		web.Address("0.0.0.0:9999"), // 服务端口
	)
	srv.Run()
}
